/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 */

import React, {useState, useEffect} from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import LoginScreen from './src/screens/Login/LoginScreen';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import {MainTabNavigator} from "./src/navigation/MainTabNavigator.tsx";
import {dictManager} from './src/utils/dictManager';
import {useAuthStore} from './src/store/authStore';
import {View, ActivityIndicator, StatusBar} from 'react-native';

// 为路由定义类型
export type RootStackParamList = {
    Login: undefined;
    Main: undefined;
};

const Stack = createNativeStackNavigator<RootStackParamList>();

// 一个简单的启动屏组件
const SplashScreen = () => (
    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
        <ActivityIndicator size="large" />
    </View>
);

function App(): React.JSX.Element {
    // 使用 Zustand store 的状态
    const accessToken = useAuthStore((state) => state.accessToken);
    // isHydrated 用来追踪 Zustand 状态是否已从 AsyncStorage 恢复
    const [isHydrated, setIsHydrated] = useState(false);

    useEffect(() => {
        // 监听 Zustand persist 中间件的水合（hydration）完成事件
        const unsubscribe = useAuthStore.persist.onFinishHydration(() => {
            setIsHydrated(true);
        });

        // 预加载字典数据
        dictManager.preloadLeaveDictionaries();

        return () => {
            unsubscribe();
        };
    }, []);

    // 在状态从 AsyncStorage 恢复之前，显示启动屏
    if (!isHydrated) {
        return <SplashScreen />;
    }

    return (
        <SafeAreaProvider>
            <NavigationContainer>
                <Stack.Navigator initialRouteName={accessToken ? 'Main' : 'Login'}>
                    <Stack.Screen
                        name="Login"
                        component={LoginScreen}
                        options={{headerShown: false}}
                    />
                    <Stack.Screen
                        name="Main"
                        component={MainTabNavigator}
                        options={{headerShown: false}}
                    />
                </Stack.Navigator>
            </NavigationContainer>
        </SafeAreaProvider>
    );
}

export default App;
